package handle

import (
	"encoding/json"
	"novel-worlds/cache"
	"novel-worlds/model"
	"novel-worlds/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func User(c *gin.Context) {
	password := c.PostForm("password")
	username := c.PostForm("username")
	if password == "" || username == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user model.User
	model.DB.Where("username = ?", username).First(&user)
	cache_Key := "pass" + username
	cacheCount, _ := cache.Rdb.Get(cache.Ctx, cache_Key).Int()
	if cacheCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, cache_Key)
		if cacheCount == 2 {
			cache.Rdb.Set(cache.Ctx, cache_Key, "3", time.Hour*3)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误封3小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	name := c.PostForm("name")
	state := c.PostForm("state")
	text := c.PostForm("text")
	node := model.Novel{
		Title: title,
		Name:  name,
		State: state,
		Text:  text,
	}
	err := model.DB.Create(&node).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size
	var count int64
	model.DB.Model(&model.Novel{}).Count(&count)
	cache_Key := "page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_Key).Result()
	var node []model.Novel
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&node)
		jsonData, _ := json.Marshal(node)
		cache.Rdb.Set(cache.Ctx, cache_Key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &node)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  node,
		"count": count,
	})
}

func Login(c *gin.Context) {
	id := c.Query("id")
	var nodes []model.Novel
	cache_Key := "page" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_Key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).First(&nodes)
		jsonData, _ := json.Marshal(nodes)
		cache.Rdb.Set(cache.Ctx, cache_Key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &nodes)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": nodes,
	})
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var node model.Novel
	model.DB.Where("id=?", id).Delete(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
